<template>
	<view>
		<view class="confirm-order">
			<view class="confirm-con">
				

				<view class="goods contain">
					<order-goods :team="{ need: orderInfo.team_need }" :list="goodsLists"  :order_type="orderInfo.order_type" mode="comfirm"></order-goods>
					<!-- <view class="item row-between">
						<view>配送方式</view>
						<view>快递</view>
					</view> -->
					<view class="item row-between">
						<view>买家留言</view>
						<u-input v-model="userRemark" class="flex1 ml20" :clearable="false"
							placeholder="请添加备注（150字以内）"></u-input>
					</view>
				</view>
			</view>
			<view class="footer bg-white row-between fixed">
				<view class="all-price lg row">
					<text>合计：</text>
					<view class="primary">
						<price-format :first-size="36" :second-size="36" :price="orderInfo.order_amount"></price-format>
					</view>
				</view>
				<button class="btn br60 white" size="md" hover-class="none" @tap="onSubmitOrder">
					提交订单
				</button>
			</view>
		</view>
		<loading-view v-if="showLoading" background-color="transparent" :size="50"></loading-view>
		<loading-view v-if="isFirstLoading"></loading-view>
	</view>
</template>

<script>
	import {
		orderBuy,
		getOrderCoupon,
		getDelivery
	} from "@/api/order";
	import {
		teamBuy
	} from "@/api/activity";
	import {
		prepay,
		getMnpNotice,
		getPayway
	} from "@/api/app";
	import {
		wxpay,
		alipay
	} from "@/utils/pay";

	export default {
		data() {
			return {
				isFirstLoading: true, // 首次页面加载loading
				showLoading: false, // Loading: 显示 | 隐藏
				orderInfo: {}, // 订单信息
				goodsLists: [], // 商品列表
				bargainLaunchId: -1,
				userRemark:''
			};
		},

		onLoad(options) {
			const data = JSON.parse(decodeURIComponent(options.data));
			this.goods = data.goods;
			this.type = data.type;

			this.handleOrderMethods("info");
			uni.$on("payment", (params) => {
				setTimeout(() => {
					uni.$off("payment");

					if (params.result) {
						uni.redirectTo({
							url: `/pages/pay_result/pay_result?id=${params.order_id}`,
						});
					} else {
						uni.redirectTo({
							url: "/pages/user_order/user_order",
						});
					}
				}, 500);
			});
		},

		onUnload() {
			// 取消全局监听
			uni.$off(["selectaddress", "store"]);
		},

		methods: {
			// 更改配送方式
			changeDelivery(index) {
				this.addressTabsIndex = index;
				this.handleOrderMethods("info");
			},

			// 点击选择收货地址
			onAddressExpress() {
				uni.navigateTo({
					url: `/pages/user_address/user_address?type=${1}`,
				});
			},

			// 点击门店自提
			onAddressStore() {
				uni.navigateTo({
					url: `/bundle/pages/store_list/store_list`,
				});
			},

			// 更改积分使用
			changeIntegral() {
				const useIntegral = this.useIntegral;

				const orderInfo = this.orderInfo;
				const integral_limit = orderInfo.integral_limit;
				const user_integral = orderInfo.user_integral;

				if (integral_limit > user_integral)
					return this.$toast({
						title: "未满足使用条件"
					});

				this.useIntegral = useIntegral ? 0 : 1;
				this.$nextTick(() => this.handleOrderMethods("info"));
			},

			// 积分使用说明Dialog
			dialogIntegralDesc() {
				const desc = this.orderInfo.integral_desc;

				uni.showModal({
					title: "积分使用说明",
					content: desc,
					confirmColor: "#FF2C3C",
					showCancel: false,
				});
			},

			// 选择优惠券
			onSelectCoupon(value) {
				this.couponId = value;
				this.showCoupon = false;
				this.handleOrderMethods("info");
			},

			// 获取微信授权
			authWechatMessage() {
				return new Promise((resolve, reject) => {
					getMnpNotice({
							scene: 1,
						})
						.then(({
							code,
							data,
							msg
						}) => {
							if (code != 1) throw new Error(msg);
							return data;
						})
						.then((data) => {
							if (!data.length) return reject();
							uni.requestSubscribeMessage({
								tmplIds: data,
								success(res) {
									resolve(res);
								},
								fail(err) {
									reject(err);
								},
							});
						})
						.catch((err) => {
							reject(err);
						});
				});
			},

			// 点击订单提交
			onSubmitOrder() {
				uni.showModal({
					title: "温馨提示",
					content: "是否确认下单?",
					confirmColor: "#FF2C3C",
					success: ({
						confirm
					}) => {
						if (!confirm) return;

						// #ifdef MP-WEIXIN
						this.authWechatMessage()
							.catch((err) => {
								console.log(err);
							})
							.finally(() => {
								this.handleOrderMethods("submit");
							});
						// #endif

						// #ifndef MP-WEIXIN
						this.handleOrderMethods("submit");
						// #endif
					},
				});
			},

			// 初始化优惠券数据
			initCouponData() {
				
			},

			// 初始化页面数据
			async initPageData(from) {
				this.showLoading = true;

				try {
					const {
						code,
						data,
						msg
					} = this.teamId ?
						await teamBuy(from) :
						await orderBuy(from);

					if (code == 1) {
						this.address = data.address;
						this.goodsLists = data.goods_lists;
						this.orderInfo = data;
						this.$nextTick(() => {
							this.isFirstLoading = false;
						});
					} else {
						throw new Error(msg);
					}
				} catch (err) {
					console.log(err);
					this.$toast({
						title: "网络异常，请重新进入页面"
					});
				} finally {
					this.showLoading = false;
				}
			},

			// 订单提交
			async handleOrderSubmit(from) {
				this.showLoading = true;

				from.remark = this.userRemark;
				from.type = this.type;

				try {
					const {
						code,
						data,
						msg
					} = this.teamId ?
						await teamBuy(from) :
						await orderBuy(from);

					if (code == 1) {
						uni.redirectTo({
							url: `/pages/payment/payment?from=${data.type}&order_id=${data.order_id}`,
						});
					} else {
						throw new Error(msg);
					}
				} catch (err) {
					console.log(err);
					// this.$toast({ title: '下单异常，请重新操作' })
				} finally {
					this.showLoading = false;
				}
			},

			// 订单处理
			handleOrderMethods(action) {
				// 订单提交数据
				const orderFrom = {
					action,
					item_id: this.goods[0].item_id,
					bargain_launch_id: this.bargainLaunchId == -1 ? "" : this.bargainLaunchId,
				};

				switch (action) {
					case "info":
						this.initPageData(orderFrom);
						break;
					case "submit":
						this.handleOrderSubmit(orderFrom);
						break;
				}
			},
		},
	};
</script>
<style>
	.confirm-order .confirm-con {
		overflow: hidden;
		padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
	}

	.confirm-order .contain {
		border-radius: 14rpx;
		margin: 20rpx 20rpx 0;
		background-color: #fff;
		overflow: hidden;
	}

	.confirm-order .img-line {
		height: 1.5px;
		width: 100%;
		display: block;
	}

	.confirm-order .coupons {
		height: 100rpx;
		padding: 0 24rpx;
	}

	.goods .title {
		padding: 22rpx 24rpx;
		border-bottom: 1px solid #f6f6f6;
	}

	.goods .all-num {
		padding: 22rpx 24rpx;
		border-bottom: 1px dotted #f6f6f6;
	}

	.confirm-order .footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		padding: 0 30rpx;
		box-sizing: content-box;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.confirm-order .price {
		padding: 28rpx 20rpx;
	}

	.confirm-order .price .item:not(:last-of-type) {
		margin-bottom: 20rpx;
	}

	.confirm-order .goods>.item,
	.confirm-order .benefit>.item {
		padding: 0 24rpx;
		height: 80rpx;
	}

	.confirm-order .btn {
		background: linear-gradient(90deg,
				rgba(249, 95, 47, 1) 0%,
				rgba(255, 44, 60, 1) 100%);
		background: #2CA4FF;
		padding: 0 50rpx;
	}

	.confirm-order .van-cell:after {
		border: none;
	}

	.goods .shop-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.pop-title {
		height: 100rpx;
		border-bottom: 1rpx solid #f2f2f2;
	}

	.pop-title .title {
		margin-left: 30rpx;
		font-size: 34rpx;
		font-weight: bold;
		line-height: 36rpx;
	}

	.receiving-way {
		margin: 20rpx 20rpx 0 20rpx;
		border-radius: 7px;
		background-color: #ffffff;
		overflow: hidden;
	}

	.receiving-card {
		display: flex;
		align-items: center;
		min-height: 160rpx;
		padding: 20rpx;
		border-top: 1px solid #f2f2f2;
	}

	.receiving-content {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.store-from {
		padding: 0 20rpx;
		font-size: 28rpx;
	}

	.store-from-item {
		display: flex;
		align-items: center;
		height: 100rpx;
	}

	.store-from-item:nth-child(n + 2) {
		border-top: 1px dashed #f2f2f2;
	}
</style>